package org.example.util;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.bean.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class JwtAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws IOException {
        // 1. 从Header获取token
        String token = request.getHeader("Authorization");
        //token=Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJjYyIsImlhdCI6MTc1MzkzMDEyOSwiZXhwIjoxNzUzOTY2MTI5fQ.kJarjzBdifD6eaC8zNLUg2EsgIC3nIOoI0I2xu_5hT4
        System.out.println("从header获取的token="+token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
        }
        // 2. 验证token有效性
        String username=jwtUtils.extractUserName(token);
        if(username==null){
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效token");
            return false;
        }
        User user=userService.findByUsername(username);
        if(user==null){
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效token");
            return false;
        }
        if(!jwtUtils.validateToken(token,user)){
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效token");
            return false;
        }

        // 3. 将用户信息存入请求
        String userName = jwtUtils.extractUserName(token);
        request.setAttribute("currentUserName", userName);

        return true;
    }
}